package com.spring.common.redis.config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * Created by liuyang on 2016/12/18.
 */
public class JedisClusterFactory {
    private static final Log logger = LogFactory.getLog(JedisClusterFactory.class);
    private String jedisClusterPool ;
    private String passWord;
    public static JedisCluster jedisCluster;
    private Integer timeout;
    private Integer connectionTimeout;
    private Integer maxRedirection;
    private GenericObjectPoolConfig genericObjectPoolConfig;
    private Pattern p = Pattern.compile("^.+[:]\\d{1,5}\\s*$");

    private void initJedisCluster() throws Exception {
        try {
            String[] poolArray = jedisClusterPool.split(",");
            Set<HostAndPort> hostAndPortList = new HashSet<HostAndPort>();
            for (int i = 0;i < poolArray.length; i++){
                boolean isIpPort = p.matcher(poolArray[i]).matches();
                if (!isIpPort) {
                    throw new IllegalArgumentException("ip 或 port 不合法");
                }
                String[] ipAndPort = poolArray[i].split(":");
                HostAndPort hostAndPort = new HostAndPort(ipAndPort[0], Integer.parseInt(ipAndPort[1]));
                hostAndPortList.add(hostAndPort);
            }
            jedisCluster = new JedisCluster(hostAndPortList, connectionTimeout,timeout, maxRedirection,passWord,genericObjectPoolConfig);
            logger.info("加载成功");
        } catch (Exception ex) {
            throw new Exception("解析 jedis 配置文件失败", ex);
        }
    }



    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public void setMaxRedirection(Integer maxRedirection) {
        this.maxRedirection = maxRedirection;
    }

    public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) {
        this.genericObjectPoolConfig = genericObjectPoolConfig;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setJedisClusterPool(String jedisClusterPool) {
        this.jedisClusterPool = jedisClusterPool;
    }

    public void setConnectionTimeout(Integer connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
    }
}
